<script lang="ts">
import {defineComponent, PropType, h} from "vue"

/**
 * 文本高亮组件
 */
export default defineComponent({
  name: "HighlightText",
  props: {
    content: {//文本内容
      type: String,
      required: true
    },
    keyword: {//高亮内容
      type: Array as PropType<string[]>,
      default: []
    },
    color: {//高亮颜色
      type: String,
      default: '#ff0000'
    },
    bold: {//
      type: Boolean,
      default: false
    }
  },
  setup(props) {
    let {content, keyword, color, bold} = props;
    return () => {
      if (keyword.length === 0) {
        return h('div', {innerHTML: content})
      }
      for (let key of keyword) {
        content = content.replace(new RegExp(key, 'g'), match => {
          return bold ? `<span style="color:${color};font-weight:bold;">${match}</span>` : `<span style="color:${color}">${match}</span>`
        })
      }
      return h('div', {innerHTML: content})
    }
  }
})
</script>